import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { HeroService } from '../../services/hero.service';
import { NzModalService } from 'ng-zorro-antd';
import { Observable} from 'rxjs';

import {
  FormBuilder,
  FormControl,
  FormGroup,
  Validators
} from '@angular/forms';

@Component({
  selector: 'app-forgetpwd',
  templateUrl: './forgetpwd.component.html',
  styleUrls: ['./forgetpwd.component.scss']
})
export class ForgetpwdComponent implements OnInit {

  validateForm: FormGroup;
  btn_loading=false;
  errorTips:string;
  captchaBtn:string="获取验证码";
  checkCaptchaCode:number;

  submitForm(): void {
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[ i ].markAsDirty();
      this.validateForm.controls[ i ].updateValueAndValidity();
    }
  }

  constructor(private heroService: HeroService,
              private fb: FormBuilder,
              private router: Router,
              private modalService: NzModalService) {
  }

  phoneNUmberValidator = (control: FormControl): { [ s: string ]: boolean } => {
    if (!control.value) {
      return { required: true };
    } else if (!(/^1\d{10}$/.test(control.value))) {
      return { confirm: true, error: true };
    }
  }

  ngOnInit(): void {
    this.validateForm = this.fb.group({
      username: [ null, [ Validators.required ] ],
      phoneNumberPrefix: [ '+86' ],
      phoneNumber: [ null, [ Validators.required ] ],
      captcha : [ null ],
      password: [ null ]
    });
  }

  getCaptcha(username,phoneNumber){
    if(username && phoneNumber){
      let url=host+"/main/resetPwd/getValidate?username="+username+"&mobile="+phoneNumber; 
      this.heroService.get(url).then(result=>{
        console.log(result);
        const observable$ = Observable.create(observer => {//创建observable
          let index = 60;
          observer.next(index);
          setInterval(() => {
              index--;
              observer.next(index);//执行
          }, 1000);
        });
        if(result.code==0){
          const subscription = observable$.subscribe(value => {//订阅observable
            this.captchaBtn="已发送 " + value;
              if (value === 0) {
                  subscription.unsubscribe();//清理,即取消订阅
                  this.captchaBtn="重新发送？"
                  this.errorTips="";
              }
          });
        }else{
          this.errorTips=result.msg;
        }
      });
    }
  }

  checkCaptcha(event){
    console.log(event.target.value);
    if(event.target.value){
      let url=host+"/main/resetPwd/checkValidate";
      let model='username='+this.validateForm.value.username+'&mobile='+this.validateForm.value.phoneNumber+'&validate='+event.target.value;
      this.heroService.post(url,model).then(result=>{
        // console.log(result);
        if(result.code==0){
          this.checkCaptchaCode=1;
        }else{
          this.checkCaptchaCode=-1;
        }
      });
    }
  }  

  focusCheck(){
    this.checkCaptchaCode=0;
  }
  cancelErrorTips(){
    this.errorTips="";
  }

  forgetPwd() {
    this.validateForm.get('captcha')!.setValidators(Validators.required);
    this.validateForm.get('captcha')!.markAsDirty();
    this.validateForm.get('password')!.setValidators(Validators.required);
    this.validateForm.get('password')!.markAsDirty();
    if(this.validateForm.status=="VALID"){
      this.btn_loading=true;
      let url=host+"/main/resetPwd/resetPassword";
      let model='username='+this.validateForm.value.username+'&mobile='+this.validateForm.value.phoneNumber+'&validate='+this.validateForm.value.captcha+'&password='+this.validateForm.value.password;
      this.heroService.post(url,model).then(result=>{
          this.btn_loading=false;
          if(result.code==0){
            this.modalService.success({
              nzTitle: '提示',
              nzContent: '重设密码成功,请登录'
            });
            this.router.navigate(['/login']);
          }else{
            this.errorTips=result.data;
          }
      })
    }
  }
  checkMobile(){
    this.validateForm.get('phoneNumber')!.setValidators(this.phoneNUmberValidator);
    this.validateForm.get('phoneNumber')!.markAsDirty();
    this.validateForm.get('phoneNumber')!.updateValueAndValidity();
  }
  clearCheckMobile(){
    this.validateForm.get('phoneNumber')!.clearValidators();
    this.validateForm.get('phoneNumber')!.markAsPristine();
    this.validateForm.get('phoneNumber')!.updateValueAndValidity();
  }
}
